package at.irian.jsfatwork.broker.domain.account;

import at.irian.jsfatwork.broker.domain.stock.Stock;
import at.irian.jsfatwork.broker.domain.stock.StockExchange;
import at.irian.jsfatwork.broker.domain.stock.Quote;
import at.irian.jsfatwork.broker.domain.BaseEntity;
import org.hibernate.annotations.ForeignKey;

import javax.persistence.*;
import java.util.Date;
import java.math.BigDecimal;

/**
 * @author Thomas Spiegl
 */
@Entity
public class SecuritiesAccountPosition extends BaseEntity {

    private Stock stock;

    private Integer quantity;

    private Date bookingDateTime;

    private Long id;

    /**
     * Protected access - only SecuritiesAccount is allowed to create positions.
     */
    protected SecuritiesAccountPosition() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToOne(optional = false)
    @ForeignKey(name = "stock_id")
    public Stock getStock() {
        return stock;
    }

    public void setStock(Stock stock) {
        this.stock = stock;
    }

    @Basic(optional = false)
    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    @Basic(optional = false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date getBookingDateTime() {
        return bookingDateTime;
    }

    public void setBookingDateTime(Date bookingDateTime) {
        this.bookingDateTime = bookingDateTime;
    }

    public void accountBalance(SecuritiesAccountBalance balance) {
        balance.add(this.stock, this.quantity);
    }


    @Transient
    public BigDecimal getCurrentAmount(StockExchange stockExchange) {
        Quote quote = stockExchange.getQuote(this.getStock());
        return quote.getAmount().multiply(new BigDecimal(this.getQuantity()));
    }

}
